<template>
  <div class="app-container">
    <div class="button-container">
      <el-button type="primary" @click="goBack">返回</el-button>
      <span>
        <el-button type="primary" @click="saveData">保存</el-button>
        <el-button type="primary" @click="addItem">新增一行</el-button>
        <el-button type="primary" @click="goToList">列表</el-button>
        <el-button type="danger" @click="deleteSelected">批量删除</el-button>
        <el-button type="primary" @click="printToPDF">打印PDF</el-button>
      </span>
    </div>
    <table class="leave-register-table">
      <caption>
        <h2 style="font-size: 1.2em">员工离岗登记表</h2>
      </caption>
      <thead>
        <tr>
          <th>
            <input
              type="checkbox"
              v-model="isAllSelected"
              @change="toggleSelectAll"
            />
          </th>
          <th>日期</th>
          <th>部门</th>
          <th>组别</th>
          <th>离岗起止时间</th>
          <th>责任人</th>
          <th>备注</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in leaveList" :key="index">
          <td>
            <input type="checkbox" v-model="selectedItems" :value="index" />
          </td>
          <td>
            <el-date-picker
              v-model="item.leaveDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 140px"
            >
            </el-date-picker>
          </td>
          <td><input v-model="item.deptName" /></td>
          <td><input v-model="item.teamGroup" /></td>
          <td>
            <el-time-picker
              v-model="item.leaveTimeRange"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="HH:mm:ss"
              format="HH:mm"
              style="width: 240px"
            >
            </el-time-picker>
          </td>
          <td><input v-model="item.responsiblePerson" /></td>
          <td><input v-model="item.remark" /></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="7">
            <span
              style="
                display: flex;
                justify-content: space-between;
                font-size: 0.9em;
                color: #757575;
              "
              ><span>表单编号及版本：AM-JY-199 A/0</span>
              <span>保存期限：长期</span></span
            >
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { saveLeaveRegister } from "@/api/leaveRegister";

export default {
  data() {
    return {
      leaveList: [
        {
          leaveDate: "",
          deptName: "",
          teamGroup: "",
          leaveTimeRange: ["09:00:00", "18:00:00"],
          responsiblePerson: "",
          remark: "",
        },
      ],
      selectedItems: [],
      isAllSelected: false,
    };
  },
  methods: {
    addItem() {
      this.leaveList.push({
        leaveDate: "",
        deptName: "",
        teamGroup: "",
        leaveTimeRange: ["09:00:00", "18:00:00"],
        responsiblePerson: "",
        remark: "",
      });
    },
    saveData() {
      const formattedData = this.leaveList.map((item) => ({
        ...item,
        leaveTimeRange: item.leaveTimeRange
          ? `${item.leaveTimeRange[0]}-${item.leaveTimeRange[1]}`
          : "",
      }));

      saveLeaveRegister(formattedData)
        .then(() => {
          this.$message({
            type: "success",
            message: "保存成功！",
          });
          this.goToList();
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: "保存失败：" + error.message,
          });
        });
    },
    goBack() {
      this.$router.push("/main/renshi/renshizhidu");
    },
    printToPDF() {
      const doc = new jsPDF("p", "pt", "a4");
      const element = document.querySelector(".leave-register-table");
      html2canvas(element).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");
        const imgWidth = 522;
        const pageHeight = 841.89;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let positionY = 0;
        if (imgHeight >= pageHeight) {
          let leftHeight = imgHeight;
          while (leftHeight >= pageHeight) {
            doc.addImage(imgData, "PNG", 40, positionY, imgWidth, pageHeight);
            positionY += pageHeight;
            doc.addPage();
            leftHeight -= pageHeight;
          }
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, leftHeight);
        } else {
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, imgHeight);
        }
        doc.save("员工离岗登记表.pdf");
      });
    },
    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedItems = this.leaveList.map((_, index) => index);
      } else {
        this.selectedItems = [];
      }
    },
    deleteSelected() {
      if (this.selectedItems.length === 0) {
        this.$message({
          message: "请选择要删除的记录",
          type: "warning",
        });
        return;
      }

      // 弹出确认框
      this.$confirm("此操作将永久删除选中的记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 对选中的索引进行降序排序，避免删除元素时索引混乱
          this.selectedItems.sort((a, b) => b - a);
          this.selectedItems.forEach((index) => {
            this.leaveList.splice(index, 1);
          });
          this.selectedItems = [];
          this.isAllSelected = false;

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    goToList() {
      this.$router.push("/main/renshi/renshizhidu/ygligangdjb/ygligangdjbList");
    },
    goBack() {
      this.$router.push(
        "/main/renshi/renshidiaodong/yuangonglizhi/yuangonglizhi"
      );
    },
  },
  watch: {
    selectedItems: {
      handler(newVal) {
        this.isAllSelected = newVal.length === this.leaveList.length;
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
::v-deep .el-input__inner {
  border: none;
}
.app-container {
  padding: 10px;
  width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 20px);
  background-color: #fff;
}

.button-container {
  /* margin-bottom: 20px; */
  display: flex;
  justify-content: space-between;
}

.button-container .el-button {
  margin-right: 10px;
}

.leave-register-table {
  border-collapse: collapse;
  width: 100%;
  margin-top: 10px;
}

.leave-register-table td,
.leave-register-table th {
  border: 1px solid #ccc;
  padding: 5px;
  text-align: center;
}

input {
  border: 0px;
}
</style>